package com.luo.backend.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * 邮件发送服务
 */
@Service
public class EmailService {
    
    private static final Logger logger = LoggerFactory.getLogger(EmailService.class);
    
    @Autowired
    private JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String fromEmail;
    
    /**
     * 发送简单文本邮件
     */
    public void sendSimpleEmail(String toEmail, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(toEmail);
            message.setSubject(subject);
            message.setText(content);
            
            mailSender.send(message);
            logger.info("邮件发送成功 - 收件人: {}, 主题: {}", toEmail, subject);
        } catch (Exception e) {
            logger.error("邮件发送失败 - 收件人: {}, 错误: {}", toEmail, e.getMessage());
            throw new RuntimeException("邮件发送失败: " + e.getMessage());
        }
    }
    
    /**
     * 发送验证码邮件
     */
    public void sendVerificationCode(String toEmail, String code, String type) {
        String subject = "【美食拼单】验证码";
        String content = buildVerificationEmailContent(code, type);
        sendSimpleEmail(toEmail, subject, content);
    }
    
    /**
     * 构建验证码邮件内容
     */
    private String buildVerificationEmailContent(String code, String type) {
        String typeText = getTypeText(type);
        
        return String.format(
            "您的验证码是：%s\n\n" +
            "验证码5分钟内有效，请勿泄露给他人。\n\n" +
            "类型：%s\n" +
            "如非本人操作，请忽略此邮件。\n\n" +
            "------------------------------\n" +
            "美食拼单平台",
            code,
            typeText
        );
    }
    
    /**
     * 获取验证码类型文本
     */
    private String getTypeText(String type) {
        switch (type) {
            case "register":
                return "注册账号";
            case "reset_password":
                return "重置密码";
            case "change_email":
                return "修改邮箱";
            default:
                return "身份验证";
        }
    }
}



